<template>
    <d2-container v-loading="vLoading"  element-loading-text="加载查询条件中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
        <div id="totalHeader" slot="header">
            <div style="width:100%">
                <avue-form v-model="form" :option="option">
                    <template slot="menuForm">
                        <el-button type="primary" size="small" icon="el-icon-search" @click="search" :loading="searchLoading">查询</el-button>
                        <el-button type="primary" size="small" icon="el-icon-more" @click="newWindow">新窗口</el-button>
                        <el-button type="primary" size="small" icon="el-icon-printer" @click="printer">直接打印</el-button>
                        <el-button type="primary" size="small" icon="el-icon-download" @click="exportPDF">导出PDF</el-button>
                        <el-button type="primary" size="small" icon="el-icon-download" @click="exportExcel">导出Excel</el-button>
                    </template>
                </avue-form>
            </div>
        </div>
        <iframe id='rpIfr' name="rpIfr" style="position: absolute;top: 0;right: 0;left: 0;bottom: 0;width: 100%;height: 100%"
                frameborder='0' scrolling='auto'></iframe>
        <iframe id='savIfr' name="savIfr"
                style="display: none; width: 100%; height: 100%;" frameborder='0'
                scrolling='no'></iframe>
        <iframe id='savExcelIfr' name="savExcelIfr"
                style="display: none; width: 100%; height: 100%;" frameborder='0'
                scrolling='no'></iframe>
    </d2-container>
</template>

<script>
    import qs from 'qs'
    import Kit from '@/libs/kit.js'

    let self = null
    let DIC = {
        reports: [],
        drivers: [],
        vehicles: [],
        lines:[]
    }

    let conditionMap = {
        'daterange': {
            label: '日期选择',
            prop: 'daterange',
            type: 'daterange',
            span: 6,
            valueFormat: "yyyy-MM-dd"
        },
        'DriverId':{
            label: '司机选择',
            prop: 'DriverId',
            multiple: true,
            type: 'select',
            span: 6,
            dicData: 'drivers',
        },
        'VehicleId':{
            label: '车辆选择',
            prop: 'VehicleId',
            multiple: true,
            type: 'select',
            span: 6,
            dicData: 'vehicles',
        },
        'LineId':{
            label: '线路选择',
            prop: 'LineId',
            multiple: true,
            type: 'select',
            span: 6,
            dicData: 'lines',
        }
    }
    export default {
        name: "total",
        data(){
            return {
                vLoading: false,
                form: {},
                option:{
                    menuPostion: 'left',
                    submitBtn: false,
                    emptyBtn: false,
                    dicData: DIC,
                    column: [{
                        label: '报表',
                        prop: 'reportType',
                        type: 'tree',
                        span: 6,
                        parent:  false,
                        dicData: 'reports',
                        rules: [{
                            required: true,
                            message: "请选择报表",
                            trigger: "change"
                        }]
                    }]
                },
                condition:[],
                searchLoading: false,
                _extAgentMode: false,
            }
        },
        watch:{
           'form.reportType':{
               handler(newValue,oldValue){
                   if(newValue)
                    self.loadReportCondition()
               }
           }
        },
        methods:{
            agentKit(){
                let t = this
                let tmp = Kit.proc({
                    'method' : 'getProps'
                });
                if (tmp && tmp[0] == '0') {
                    t._extAgentMode = true;
                }
            },
            loadDicData(){
                let t = this
                t.$axios.get('safe/safe/getDriverId').then(res => {
                    let dic = []
                    res.data.forEach(d=>{
                        dic.push({
                            label: d.text,
                            value: d.id
                        })
                    })
                    DIC.drivers = dic
                }).catch(err => {
                    t.$message.error('获取失败! ' + err && err.message)
                })

                t.$axios.get('safe/safe/getVehicleId').then(res => {
                    let dic = []
                    res.data.forEach(d=>{
                        dic.push({
                            label: d.text,
                            value: d.id
                        })
                    })
                    DIC.vehicles = dic
                }).catch(err => {
                    t.$message.error('获取失败! ' + err && err.message)
                })

                t.$axios.get('/safe/safe/getSel?key=line').then(res => {
                    let dic = []
                    res.data.forEach(d=>{
                        dic.push({
                            label: d.text,
                            value: d.id
                        })
                    })
                    DIC.lines = dic
                }).catch(err => {
                    t.$message.error('获取失败! ' + err && err.message)
                })
            },
            loadReport(){
                let t = this
                t.$axios.post(
                    '/datan/report',
                   qs.stringify( {
                       protype:1
                   })
                ).then( res =>{
                    DIC.reports = res.data
                }).catch(err =>{
                    t.$message.error(err && err.message)
                }).finally(()=>{
                })
            },
            loadReportCondition(){
                let t = this
                if(t.vLoading)return
                t.vLoading = true
                if(t.form.reportType !== ''){
                    let report = t.form.reportType.split('@')
                    t.$axios.post(
                        '/datan/report',
                        qs.stringify({
                            protype: 3,
                            rpType: report[0],
                            rpName: report[1]
                        })
                    ).then( res =>{
                        t.condition = res.data
                        t.getConditionInput()
                    }).catch(err =>{
                        t.$message.error(err && err.message)
                    }).finally(()=>{
                        t.vLoading = false
                    })
                }
            },
            getConditionInput(){
               let t = this
                Object.keys(t.form).forEach(key=>{
                    if(!Object.is(key,'reportType')){
                        delete t.form[key]
                    }
                })
               t.option.column = [t.option.column[0]]

               if(t.condition.length>0){
                   if(t.condition.indexOf('be') > -1  && t.condition.indexOf('ed') > -1){
                       t.option.column.push(conditionMap['daterange'])
                   }
                   if(t.condition.indexOf('DriverId') > -1){
                       t.option.column.push(conditionMap['DriverId'])
                   }
                   if(t.condition.indexOf('VehicleId') > -1){
                       t.option.column.push(conditionMap['VehicleId'])
                   }
                   if(t.condition.indexOf('LineId') > -1){
                       t.option.column.push(conditionMap['LineId'])
                   }
               }
            },
            parsePara(protype){
                let t = this
                if(t.form.reportType === ''){
                    return null
                }
                let report = t.form.reportType.split('@')
                let sp = {
                    'rp_title' : report[1]
                }
                Object.keys(t.form).forEach(key=>{
                    if(key !== 'reportType'){
                        if(key === 'daterange'){
                           if(t.form[key] === null || t.form[key] === ''){
                               sp['be'] = ''
                               sp['ed'] = ''
                           }else{
                               sp['be'] = t.form[key][0]
                               sp['ed'] = t.form[key][1]
                           }
                        }else if(Object.is(key,'DriverId') || Object.is(key,'VehicleId') || Object.is(key,'LineId')){
                            sp[key] = t.form[key].join(",")
                        }
                    }
                })
                //报表类别、名参数,form参数
                let paramObj = {
                    'rpType': report[0],
                    'rpName': report[1],
                    'protype': protype ? protype : '98',
                    'rpparajson': JSON.stringify(sp),
                    'sqlparajson': JSON.stringify(sp)
                };
               return paramObj
            },
            search(){
                let t = this
                let paramObj = t.parsePara('98')
                if(paramObj === null){
                    t.$message.error('没有要查询的报表');
                    return;
                }
                let src = '/datan/report?' + qs.stringify(paramObj)
                let rpIfr = document.getElementById('rpIfr')
                rpIfr.src = t.$axios..baseURL + src
                rpIfr.style.height = document.body.clientHeight - document.getElementById('totalHeader').clientHeight - 200 + 'px'
            },
            newWindow(){
                let t = this
                let paramObj = t.parsePara('98')
                if(paramObj === null){
                    t.$message.error('没有要查询的报表');
                    return;
                }
                let src = '/datan/report?' + qs.stringify(paramObj)
                window.open(t.$axios.defaults.baseURL + src);
            },
            printer(){
                let t = this
                let paramObj = t.parsePara('101')
                if(paramObj === null){
                    t.$message.error('没有要打印的报表');
                    return;
                }
                let src = '/datan/report?' + qs.stringify(paramObj)

                let prop = Kit.proc({
                    'method' : 'getProps'
                });
                if (t._extAgentMode) {
                    if (!confirm('确认直接打印此报表?')) {
                        return;
                    }
                    let prnUrl = t.$axios.defaults.baseURL + src
                    Kit.proc({
                        'method' : 'prn',
                        'prm' : [ prnUrl, null ]
                    });
                } else {
                    t.$message.error('浏览器不支持此功能!请使用特定客户端打印!');
                }
            },
            exportPDF(){
                let t = this
                let paramObj = t.parsePara('101')
                if(paramObj === null){
                    t.$message.error('没有要导出的报表');
                    return;
                }
                let src = '/datan/report?' + qs.stringify(paramObj)
                if (t._extAgentMode) {
                    //如果是内置浏览器的客户端
                    //绝对路径
                    let saveUrl = t.$axios.defaults.baseURL + src
                    let d = new Date();
                    let report = t.form.reportType.split('@')
                    let saveFileName = report[1] + '_' + (d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate()) + '.pdf';
                    Kit.proc({
                        'method' : 'savFile',
                        'prm' : [ saveUrl, '导出pdf', saveFileName, 'd:\\' ]
                    });
                } else {
                    //
                    let savIfr = document.getElementById('savIfr')
                    savIfr.src = t.$axios.defaults.baseURL + src
                    savIfr.style.height = document.body.clientHeight - document.getElementById('totalHeader').clientHeight - 200 + 'px'
                }
            },
            exportExcel(){
                let t = this
                let paramObj = t.parsePara('104')
                if(paramObj === null){
                    t.$message.error('没有要导出的报表');
                    return;
                }
                let src = '/datan/report?' + qs.stringify(paramObj)
                if (t._extAgentMode) {
                    //如果是内置浏览器的客户端
                    //绝对路径
                    let saveUrl = t.$axios.defaults.baseURL + src
                    let d = new Date();
                    let report = t.form.reportType.split('@')
                    let saveFileName = report[1] + '_' + (d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate()) + '.xls';
                    Kit.proc({
                        'method' : 'savFile',
                        'prm' : [ saveUrl, '导出Excel', saveFileName, 'd:\\' ]
                    });
                } else {
                    //
                    let savExcelIfr = document.getElementById('savExcelIfr')
                    savExcelIfr.src = t.$axios.defaults.baseURL + src
                    savExcelIfr.style.height = document.body.clientHeight - document.getElementById('totalHeader').clientHeight - 200 + 'px'
                }
            }
        },
        created(){
            self = this
        },
        mounted(){
            this.loadDicData()
            this.agentKit()
            this.loadReport()
        }
    }
</script>

<style scoped>

</style>